﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using log4net;


namespace LegSec.NugetThirdPartyLicenseFileGenerator
{
    public class NuspecReader
    {
        public const string TitleAttribute = "title";
        public const string IdAttribute = "id";
        public const string VersionAttribute = "version";
        public const string LicenceNameAttribute = "licenseUrl";
        public const string LicenceUriAttribute = "licenseUrl";
        public const string ProjectUriAtribute = "projectUrl";
        public const string AuthorsAttribute = "authors";

        private static ILog LOG = LogManager.GetLogger(typeof (NuspecReader));

        private FileInfo nuspecFile;
        public FileInfo NuspecFile { get { return nuspecFile; } }

        private Dictionary<string, string> ElementDictionary = new Dictionary<string, string>();

        public NuspecReader(FileInfo nuspecFile)
        {
            this.nuspecFile = nuspecFile;
            ReadInNuspecFile();
        }

        private void ReadInNuspecFile()
        {
            XmlTextReader reader = new XmlTextReader(nuspecFile.FullName);
            while (reader.Read())
            {
                string key;
                string value; 
                if(reader.NodeType == XmlNodeType.Element)
                {
                    key = reader.Name;
                    LOG.Debug(String.Format("Read element {0}", key));
                    if(reader.Read() && !ElementDictionary.ContainsKey(key))
                    {
                        value = reader.Value;
                        ElementDictionary.Add(key, value);
                        LOG.Debug(String.Format("Adding key {0}, with Value {1}", key, value));
                    }
                }
            }
            reader.Close();
        }

        public PackageLicenseInformation GetLicenceInformationFromNuspecFile()
        {
            string titleValue;
            string versionValue;
            string authorsValue;
            string licenceUriValue;

            ElementDictionary.TryGetValue(TitleAttribute, out titleValue);
            ElementDictionary.TryGetValue(VersionAttribute, out versionValue);
            ElementDictionary.TryGetValue(AuthorsAttribute, out authorsValue);
            ElementDictionary.TryGetValue(LicenceUriAttribute, out licenceUriValue);

            if (titleValue == null || titleValue.Equals(""))
            {
                ElementDictionary.TryGetValue(IdAttribute, out titleValue);
            }

            return new PackageLicenseInformation(
                titleValue,
                versionValue,
                authorsValue,
                licenceUriValue);
        }
    }
}
